<?php
$root = $_SERVER['DOCUMENT_ROOT'] . "/php/";

include_once "$root/class/SqlConnect.php";
include_once "$root/class/SqlManager.php";

class CardKeyManager
{
    /**
     * @var SqlManager
     */
    private $sqlManager;

    public function __construct()
    {
        $sqlConnect = new SqlConnect();
        $conn = $sqlConnect->connect();
        $sqlManager = new SqlManager("card_key");
        $sqlManager->setSqlConnect($conn);
        $this->sqlManager = $sqlManager;
    }

    public function getAllCardKey()
    {
        return $this->sqlManager->getTableData();
    }

    private function jsonToCardKey($arr): CardKey
    {
        $cardKey = new CardKey($arr["key"], $arr["time"], $arr["uid"]);
        return $cardKey;
    }

    public function addCardKey(CardKey $cardKey)
    {
        $arr = array();
        $arr["key"] = $cardKey->getKey();
        $arr["time"] = $cardKey->getTime();
        $arr["uid"] = $cardKey->getUid();
        return $this->sqlManager->addFieldData($arr);
    }

    public function removeCardKey($caId)
    {
        return $this->sqlManager->deleteField($caId);
    }

    public function removeKey($key)
    {
        $arr = array();
        $arr["key"] = $key;
        return $this->sqlManager->deleteField($arr,false,true);
    }

    public function alterCardKey($caId, CardKey $cardKey)
    {
        $arr = array();
        $arr["key"] = $cardKey->getKey();
        $arr["time"] = $cardKey->getTime();
        $arr["uid"] = $cardKey->getUid();
        $this->sqlManager->alterData($caId, $arr);
    }

    public function getCardKey($key)
    {
        $arr = array();
        $arr["key"] = $key;
        return $this->sqlManager->queryFieldData($arr,false,true);
    }
}